/* -*- Mode: C++; indent-tabs-mode: nil; tab-width: 4 -*-
 * -*- coding: utf-8 -*-
 *
 * Copyright (C) 2020 KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef PLUSEAUDIOMANAGER_H
#define PLUSEAUDIOMANAGER_H

#include <QObject>

#include <pulse/error.h>
#include <pulse/pulseaudio.h>
#include <pulse/simple.h>

extern "C" {
    #include "clib-syslog.h"
}

class PulseAudioManager : public QObject
{
    Q_OBJECT
//    Q_PROPERTY(int sinkVolume MEMBER m_sinkVolume NOTIFY sinkVolumeChanged)
//    Q_PROPERTY(bool mute MEMBER m_sinkMute NOTIFY sinkMuteChanged)
public:
    explicit PulseAudioManager(QObject *parent = nullptr);
    ~PulseAudioManager();

public:
    void updateSinkInfo(const pa_sink_info* si);
    void updateSourceInfo(const pa_source_info* so);
    void setSinkVolume(int value);
    void setSinkMute(bool muted);
    void setSourceMute(bool mute);
    int getSinkVolume(){return m_sinkVolume;}
    bool getSinkMute(){return m_sinkMute;}
    bool getSourceMute(){return m_sourceMute;}

    const char* getSinkName(){return m_defaultSinkName;}
    const char* getSourceName(){return m_defaultSinkName;}

private:
    inline uint32_t volToPulseVol(int value);
    inline uint32_t volForPulseVol(int value);


protected:
    void connectPulseContext();     //链接pulse 上下文

    static void sinkInfoCallback(pa_context *c, const pa_sink_info *i, int eol, void *data);
    static void sourceInfoCallback(pa_context *c, const pa_source_info *so, int eol, void *data);
    static void serverInfoCallback(pa_context *c, const pa_server_info *i, void *data);

    static void subscribeCallback(pa_context *c, pa_subscription_event_type_t type, uint32_t idx, void *data);
    static void contextStateCallback(pa_context *c, void *data);
private:
    pa_threaded_mainloop *m_paThreadMainLoop;
    pa_context *m_paContext;
    pa_mainloop_api *m_paMainloopApi;

    pa_cvolume m_paSinkVolume;
    pa_channel_map m_channelMap;
    bool m_sinkMute;            //输出设备静音
    int m_sinkVolume;           //输出音量值
    int m_realSinkVolume;       //pulseaudio 内的音量值 131~65536
    bool m_sourceMute;          //输入设备静音

    const char* m_defaultSinkName;
    const char* m_defaultSourceName;

    float m_balance = 0.0f;

    static PulseAudioManager* s_pulseAudioManager;

Q_SIGNALS:
    void sinkVolumeChanged(int);
    void sinkMuteChanged(bool);
};

#endif // PLUSEAUDIOMANAGER_H
